package cn.bdqn.web;

import cn.bdqn.entity.Air;
import cn.bdqn.service.AirService;
import cn.bdqn.service.impl.AirServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@WebServlet(value = "/air/doUpdate")
public class AirDoUpdateServlet extends HttpServlet {
    /*
    5. 执行更新操作.
    路径:
        POST 	http://localhost/air/doUpdate
    参数:
        id = integer
        districtId = integer
        monitorTime = date
        pm10 = integer
        pm25 = integer
        monitoringStation = string
        (均为必传项)
    响应:
        1. 修改数据.
        2. 重定向到首页.
     */

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 处理POST请求中文乱码.
        req.setCharacterEncoding("UTF-8");
        //2. 直接接收全部参数.
        Map<String, String[]> allParams = req.getParameterMap();
        //3. 将allParams中的检测时间取出. 手动的转换成Date类型.
        String monitorTimeStr = allParams.get("monitorTime")[0];
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date monitorTime = null;
        try {
            monitorTime = sdf.parse(monitorTimeStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //4. 将默认的Map中的值,全部导入HashMap中.
        Map<String,Object> hashMap = new HashMap<>();
        hashMap.putAll(allParams);
        //5. 手动将HashMap中字符串的MonitorTime干掉.
        hashMap.remove("monitorTime");
        //6. 将HashMap中的值放到全新的Air对象中,
            // 再将转换完毕的monitorTime手动set到Air对象中
        Air air = new Air();
        try {
            BeanUtils.copyProperties(air,hashMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        air.setMonitorTime(monitorTime);

        //=============================================
        //1. 调用service修改空气质量信息数据
        AirService airService = new AirServiceImpl();
        Integer count = airService.updateById(air);
        //2. 重定向到首页.
        if(count == 1){
            resp.sendRedirect(req.getContextPath() + "/index");
        }
    }
}
